package springform.cli;

import java.util.Date;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;

public class GamilSender {
	public static void main(String[] args) throws Exception{
		sendSimpleMessage(args);
		//sendMimeMessage(args);
	}
	public static void sendSimpleMessage(String[] args) throws Exception{
		FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("src/main/resources/spring-gmail-sender.xml");

		System.out.println("Preparing message.");
		JavaMailSender mailSender = (JavaMailSender) ctx.getBean("gmailSender");
		SimpleMailMessage templateMessage = (SimpleMailMessage) ctx.getBean("templateMessage");
		SimpleMailMessage message = new SimpleMailMessage(templateMessage);
		message.setTo("keepitsimple12@gmail.com");
		message.setSubject("just a test");
		message.setText("Dear tester, \n"
				+ "Your email is deliver by gmail SMTP server. \n"
				+ new Date());
		
		System.out.println("Sending out email.");
		mailSender.send(message);
		
		System.out.println("Done.");
	}
	
	public static void sendMimeMessage(String[] args) throws Exception{
		FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("src/main/resources/spring-gmail-sender.xml");
		//ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();

		System.out.println("Preparing message.");
		JavaMailSender mailSender = (JavaMailSender) ctx.getBean("gmailSender");
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				mimeMessage.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress("keepitsimple12@gmail.com"));
				//mimeMessage.setFrom(new InternetAddress("mail@mycompany.com"));
				mimeMessage.setSubject("just a test");
				mimeMessage.setText("Dear tester, \n"
						+ "Your email is deliver by gmail SMTP server. \n"
						+ new Date());
			}
		};

		System.out.println("Sending out email.");
		mailSender.send(preparator);

		System.out.println("Done.");
	}

}
